// 找到头文件
#include <csignal>
#include <workflow/WFFacilities.h>
#include <wfrest/HttpServer.h>
#include <iostream>

using namespace std;

// 定义全局变量
static WFFacilities::WaitGroup waitGroup(1);

void signalhandler(int signum)
{
    waitGroup.done(); // 每done一次，等待的n就-1
}

int main()
{
    signal(SIGINT, signalhandler);

    wfrest::HttpServer server;

    server.GET("/hello", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp) { // 路径，函数对象
        cout << "hello\n";
        resp->append_output_body("hello\n"); // 基类workflow提供的
    });

    server.POST("/world", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp) { // 路径，函数对象
        cout << "world\n";
        resp->String("world\n"); // 派生类wfrest提供的
    });

    // 静态资源服务器
    server.GET("/login", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp)
               {
                   resp->File("postform.html"); // 派生类wfrest提供的
               });

    server.GET("/upload", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp)
               { 
                    resp->File("upload.html"); 
                });

     

    server.POST("/login", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp)
    {
        const std::map<std::string, std::string> &bodyMap = req->form_kv();
        for(auto it: bodyMap){
            cout << "first = " << it.first << " second = " << it.second << "\n";
        } 
    });

    // 解析查询参数
    server.POST("/login1", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp)
    {
        map<string, string> queryMap = req->query_list(); // 不触发拷贝，推荐用法
        for(auto it : queryMap){//不需要手动切割
            cout << "first = " << it.first << " second = " << it.second << "\n";
        }
    });

    
    server.POST("/login2", [](const wfrest::HttpReq *req, wfrest::HttpResp *resp, SeriesWork * series)
    {
        map<string, string> queryMap = req->query_list(); // 不触发拷贝，推荐用法
        for(auto it : queryMap){//不需要手动切割
            cout << "first = " << it.first << " second = " << it.second << "\n";
        } 

        WFRedisTask  * redisTask = WFTaskFactory::create_redis_task("redis://127.0.0.1:6379", 10, [queryMap, resp](WFRedisTask * redisTask){
            resp->String("success");
        });
        redisTask->get_req()->set_request("hget", {"62user", queryMap["username"]});
        series->push_back(redisTask);
    });

    if (server.track().start(1234) == 0)
    {
        server.list_routes(); // 列出所有支持的接口
        waitGroup.wait();
        server.stop();
    }
    else
    {
        perror("server start failed!");
        return -1;
    }

    waitGroup.wait();
    cout << "finished!\n";

    return 0;
}